import create from "zustand";
import { persist } from "zustand/middleware";
import { userLoginApi } from "@/services/user";
import { getWebStorage } from "@/libs/storage";
import getToken, { saveToken, deleteToken } from "@/libs/request/token";

export interface IUserState {
  token: string;
  logout: () => void;
  initialized: boolean;
  userInfo: API.User.UserAccount | null;
  initialization: () => Promise<void>;
  userLogin: (account: string, pin: string) => Promise<void>;
}

const persistState = persist<IUserState>(
  (set) => {
    return {
      token: "",
      product: null,
      userInfo: null,
      initialized: false,
      // 用户登出
      logout: () => {
        deleteToken();
        set({ token: "", userInfo: null });
      },
      // 用户登录
      userLogin: async (account, pin) => {
        try {
          const res = await userLoginApi({
            pin,
            account,
            type: 'USERNAME'
          });
          const expiresIn = res.expiresIn;
          const accessToken = res.accessToken;
          const refreshToken = res.refreshToken;
          const expiresAt = Date.now() + expiresIn * 1000;
          set({ token: accessToken });
          saveToken({ expiresAt, accessToken, refreshToken });
        } catch (err) {
          return Promise.reject(err);
        }
      },
      // 初始化
      initialization: async () => {
        const token = await getToken();
        set({ token, initialized: true });
      },
    };
  },
  {
    name: "user",
    getStorage: getWebStorage,
  }
);

export default create(persistState);
